import requests
import time
import jsonpath
import random
if __name__ == '__main__':
    content = input('请输入要搜索的内容：')
    pages = int(input('请输入要爬取的页数：'))
    t = 0
    for i in range(pages):
        
        pn = (i+1)*30
        # 确认图片页面的url
        url = f'https://image.baidu.com/search/acjson?tn=resultjson_com&ipn=rj&ct=201326592&is=&fp=result&queryWord={content}&cl=2&lm=-1&ie=utf-8&oe=utf-8&adpicid=&st=-1&z=&ic=0&hd=&latest=&copyright=&word={content}&s=&se=&tab=&width=&height=&face=0&istype=2&qc=&nc=1&fr=&expermode=&force=&pn={pn}&rn=30&gsm={str(hex(pn))[-2:]}&{str(int(time.time())*1000)}='
        # 创建请求头参数
        headers = {
            'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36'
            }
        # 发送请求获取响应
        response = requests.get(url,headers=headers)
        # 判断数据类型(为json类型）
        py_data = response.json()
        print(py_data)
        # 提取数据中图片的url
        img_url = jsonpath.jsonpath(py_data,'$.data[*].middleURL')
        print(i)

        for i in py_data['data']:
            if i:
                img_url = i['middleURL']
                response1 = requests.get(img_url,headers=headers)
                bytes_data = response1.content
                # 保存数据
                with open(f'{content}.{t}.jpg','wb')as f:
                    f.write(bytes_data)
                t+=1
        time.sleep(random.randint(20,40))